// ve = vue element
let ve_nav_bar;
let login_location = "/manager_login";
let default_image = "https://www.easyicon.net/api/resizeApi.php?id=1228554&size=128";
$(function () {
    validate();
    //禁止页面后撤
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });
    //---
    if (!window.location.href.endsWith(login_location))
        reLogin();

    let default_validation = { role: "", name: "", id: -1 };
    ve_nav_bar = new Vue({
        el: "#page-head",
        data: {
            validation: default_validation
        },
        methods: {
            get_paging_data(page) {
                switch (page) {
                    case "pet": ve_pet.get_paging_data(0);break;
                    case "business": ve_provider.get_paging_data(0);break;
                    case "commodity": ve_commodity.get_paging_data(0);break;
                    case "stray": ve_stray.get_paging_data(0);break;
                    case "user": ve_user.judge_if_to_show_login_box();break;
                    default:
                }
            },
            logout() {
                deleteCookie("tokenM");
                window.location.href = login_location;
            },
            is_logged_in() {
                return ve_nav_bar.validation.id > 0;
            },
            reset_info() {
                ve_nav_bar.validation = default_validation;
            },
            render_modal_box() {

            }
        },
        computed: {
            manager_name() {
                if (this.validation.id > 0)
                    return this.validation.name;
                else
                    return "ERROR";
            }
        }
    })
});

function upload_image(image, success, req) {
    if (image == null)
        return;

    let formData = new FormData();
    formData.append('file',image);

    $.ajax({
        type: "POST",
        url: "/file",
        data: formData,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 70000,
        success: success,
        error: function (xhr, status, thrown) {
            output_erro_info(status);
            console.log(req + " Error：" + status + " >" + thrown + "\n[readyState:" + xhr.readyState + ",Status:" + xhr.status + ",StatusText:" + xhr.statusText + "]")
        }
    });
}

function delete_image(image_name) {
    if (image_name == null || image_name === "")
        return;
    ajax_delete("/file/" + image_name, function (response) {
        if (response)
            console.log("deleted dirty file")
    }, "Deleting file")
}


function ajax_get(url, parameters, success, req) {
    url += "?" + $.param(parameters);
    let token = getCookie("tokenM");
    if (!url.startsWith("/auth") && (token == null || token == ""))
        window.location.href = login_location;
    ajax(url, "GET", {
        "token": token
    }, {}, success, req);
}

function ajax_post(url, data, success, req) {
    data = JSON.stringify(data);
    let token = getCookie("tokenM");
    if (!url.startsWith("/auth") && (token == null || token == ""))
        window.location.href = login_location;
    ajax(url, "POST", {
        "Content-Type": "application/json",
        "token": token
    }, data, success, req);
}

function ajax_put(url, data, success, req) {
    data = JSON.stringify(data);
    let token = getCookie("tokenM");
    ajax(url, "PUT", {
        "Content-Type": "application/json",
        "token": token
    }, data, success, req);
}

function ajax_delete(url, success, req) {
    let token = getCookie("tokenM");
    ajax(url, "DELETE", {
        "token": token
    }, {}, success, req)
}

function ajax(url, type, headers, data, success, req) {
    console.log(type + " > " + url + " " + JSON.stringify(data) + " ");
    $.ajax({
        headers: headers,
        url: url,
        type: type,
        data: data,
        timeout: 7000,
        dataType: 'json',
        success: success,
        complete: visit_complete,
        error: function (xhr, status, thrown) {
            output_erro_info(status);
            console.log(req + " Error：" + status + " >" + thrown + "\n[readyState:" + xhr.readyState + ",Status:" + xhr.status + ",StatusText:" + xhr.statusText + "]")
        }
    });
}

function visit_complete(XMLHttpRequest, textStatus) {
    let headers = XMLHttpRequest.getAllResponseHeaders().split("\r\n");
    for (let i = 0; i < headers.length; i++) {
        let parts = headers[i].split(": ");
        if (parts[0] === "token") {
            setCookie("tokenM", parts[1], 1);
            break;
        }
    }
}

function output_erro_info(status) {
    switch (status) {
        case "abort":
            alert("请求终止");
            break;
        case "parsererror":
            // window.location.href = "/";
            // alert("数据解析错误");
            break;
        case "notmodified":
            alert("内容未更改");
            break;
        case "timeout":
            alert("请求超时");
            break;
        default:
            alert("请求出错");
    }
}

function validate() {
    let token = getCookie("tokenM");
    console.log(token);
    if (!window.location.href.endsWith("/manager_login") && (token == null || token === "")) {
        window.location.href = "/manager_login";
    }
}

function getCookie(name) {
    let v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return v ? v[2] : null;
}

function setCookie(name, value, days) {
    if (value == null)
        return;

    let d = new Date;
    d.setTime(d.getTime() + 24*60*60*1000*days);
    document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}

function deleteCookie(name) { setCookie(name, '', -1); }

function reLogin() {
    ajax_post("/auth/re", {}, function (response) {
        if (response.code != null) {
            switch(response.code) {
                case "0003":
                default: {
                    deleteCookie("tokenM");
                    window.location.href = login_location
                }
            }
        } else {
            ve_nav_bar.validation = response;
        }
    }, "Re logging")
}
function imageHost() {
    return "http://" + location.host + "/images/";
}

function imageUrl(image) {
    if (image == null || image === "")
        return default_image;
    if (image.startsWith("http"))
        return image;
    return imageHost() + image;
}